package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetMealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Transactional
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetMealDishService setMealDishService;
    @Autowired
    private DishService dishService;
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("保存成功");
    }
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页显示条数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    }
    )
    public R<Page> page(int page,int pageSize,String name){
        Page<Setmeal> pageInfo=new Page<>(page,pageSize);
        Page<SetmealDto> pageDto=new Page<>();
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Setmeal::getName,name).orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,lqw);
        //拷贝普通属性到pageDto，不拷贝records
        //BeanUtils.copyProperties(pageInfo,pageDto,"records");
        pageDto.setTotal(pageInfo.getTotal());
        //组装records,先获取到records
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list=records.stream().map((item)->{
            SetmealDto setmealDto=new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            Long categoryId = item.getCategoryId();
            //获取Category对象，可以获取该对象的name了
            Category category= categoryService.getById(categoryId);
            if(category!=null){
                //获取每个record对象，取出categroyId，根据这个id获取name
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        pageDto.setRecords(list);
        return R.success(pageDto);
    }
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> dishList = setmealService.list(lqw);
        return R.success(dishList);
    }
    @PostMapping("/status/{st}")
    public R<String> updateStatus(@PathVariable int st,Long[] ids){
        //批量操作，接收id数组，遍历该数组，查看各个菜品状态
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            if(setmeal.getStatus()!=st){
                setmeal.setStatus(st);
                setmealService.updateById(setmeal);
            }
        }
        return R.success("修改状态成功");
    }
    @GetMapping("{setmealId}")
    public R<SetmealDto> getById(@PathVariable Long setmealId){
        Setmeal setmeal = setmealService.getById(setmealId);
        SetmealDto setmealDto=new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        LambdaQueryWrapper<SetmealDish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish> setmealDishList = setMealDishService.list(lqw);
        setmealDto.setSetmealDishes(setmealDishList);
        return R.success(setmealDto);
    }
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateById(setmealDto);
        //先删除原有的菜品关系
        LambdaQueryWrapper<SetmealDish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setMealDishService.remove(lqw);
        //添加新的菜品关系
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        if(setmealDishes.size()!=0){
            setmealDishes.stream().forEach((setmealDish)->{
                setmealDish.setSetmealId(setmealDto.getId());
            });
        }
        setMealDishService.saveBatch(setmealDishes);
        return R.success("修改成功");
    }
}
